package cn.whpu.cglib;

import cn.whpu.proxy.Producer;
import cn.whpu.proxy.ProducerImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理
 *
 */
public class Client {
    public static void main(String[] args) {
        final Producer producer =new ProducerImpl();
        Producer cglibProducer= (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
            /**
             *
             * @param proxy
             * @param method
             * @param args
             * @param methodProxy
             * @return
             * @throws Throwable
             */
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                //提供增强的方法
                Object returnValue =null;

                //获取方法执行的参数
                Float money = (Float) args[0];
                //判断当前方法是不是销售
                if ("saleProduct".equals(method.getName())){
                    returnValue= method.invoke(producer,money*0.8f);
                }
                return returnValue;
            }
        });
        cglibProducer.saleProduct(10000);
    }
}
